package com.liu.nb.security;

import cn.hutool.core.util.StrUtil;
import com.liu.nb.entity.SysUser;
import com.liu.nb.service.impl.SysUserService;
import com.liu.nb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* 这是一个jwt
*
* eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ
* .
* eyJzdWIiOiJ1c2VyIiwiaWF0IjoxNjI4NDA4NTU1LCJleHAiOjE2MjkwMTMzNTV9
* .
* dhvjGy8RoiJhLuGz-UDlTxjFKIdl6Mf5PwFU6ryadlrJxxKjxWfm0xefnMAZ6GckL4m4HOQZixfB5pqK82fBBA
* */
/*
@name:
@description:这个类是jwt过滤器，在访问资源之前先验证一下jwt
@author: lzy
@title: 天王盖地虎!!!
@time:  2021-08-09 19:32:07
*/
public class JwtFilter extends BasicAuthenticationFilter {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserDetailServiceImpl userDetailService;
    @Autowired
    SysUserService sysUserService;
    public JwtFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt=request.getHeader(jwtUtils.getHeader());
//        先判断jwt是否为空
        if (StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request,response);
            return;
        }
//        然后再解析jwt
        Claims claims = jwtUtils.getClaims(jwt);
        if (claims==null){
            throw new JwtException("token 异常");
        };
//        解析jwt是否过期
        if (jwtUtils.isTokenExpired(claims)){
            throw new JwtException("token 已过期");
        }
//        获得jwt解析出来的用户名
        String username= claims.getSubject();
        //获取用户权限信息
        /*
        * 获取用户权限需要用户id，但是这里没有id,只有jwt解析出来的用户名
        * 我们根据这个用户名先获取一个sysUser，然后再从sysUser中获取id
        * */
        SysUser sysUser = sysUserService.getByUsername(username);
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(username, null,
                        userDetailService.getUserAuthority(sysUser.getId()));
        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request,response);
    }
}
